package jalus.service;

import jalus.dao.CommentDAO;
import jalus.model.Comment;
import jalus.utils.PojoHandler;

import java.util.Collections;
import java.util.List;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheFactory;
import javax.cache.CacheManager;

public class CommentService {
	
	private static CommentService instance = new CommentService();
	private CommentDAO commentDAO;
	private Cache cache;
	private CommentService(){
		commentDAO = new CommentDAO();
		try {
			CacheFactory cacheFactory = CacheManager.getInstance().getCacheFactory();
			cache = cacheFactory.createCache(Collections.emptyMap());
		} catch (CacheException e) {
		}
	}
	public static CommentService getInstance(){
		return instance;
	}
	/**
	 * 获得文章的所有评论
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<jalus.pojo.Comment> getCommentByPost(Long postId){
		String key = "getCommentByPost@" + postId;
		if(!cache.containsKey(key)){
			cache.put(key, PojoHandler.copyMToPList(commentDAO.getCommentByPost(postId)));
		}
		return (List<jalus.pojo.Comment>) cache.get(key);
	}
	
	/**
	 * 新增评论
	 */
	public void addComment(Comment comment) {
		commentDAO.add(comment);
		cache.clear();
	}
	/**
	 * 删除评论
	 * @param id
	 * @return 评论所在的帖子ID
	 */
	public Long deleteCommentById(Long id) {
		cache.clear();
		return commentDAO.deleteCommentById(id);
	}
	
	/**
	 * 获取最近的评论列表
	 * @param count
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<jalus.pojo.Comment> getRecentComment(int count){
		String key = "getRecentComment@" + count;
		if(!cache.containsKey(key)){
			cache.put(key, PojoHandler.copyMToPList(commentDAO.getCommentByRange(0, count)));
		}
		return (List<jalus.pojo.Comment>) cache.get(key);
	}
	
	/**
	 * 删除和一个post相关的所有评论
	 * @param postId
	 */
	public void deleteAllcommentByPost(Long postId){
		List<jalus.pojo.Comment> commentList = getCommentByPost(postId);
		for(jalus.pojo.Comment comment : commentList){
			deleteCommentById(comment.getId());
		}
		cache.clear();
	}
}
